//
//  PTPlainSheetView.swift
//  Donpo
//
//  Created by benwang on 2020/1/14.
//  Copyright © 2020 benco. All rights reserved.
//

import UIKit
import SnapKit

extension PTSheetHandle {
    /// 双按钮消息弹框
    func sheet(title: String,
               buttons: (cancel: String, ensure: String),
               handle: Handle? = nil) {

        _sheet(title: title, message: nil, buttons: buttons, handle: handle)
    }

    /// 双按钮消息弹框
    func sheet(message: String,
               buttons: (cancel: String, ensure: String),
               handle: Handle? = nil) {

        _sheet(title: nil, message: message, buttons: buttons, handle: handle)
    }

    /// 双按钮消息弹框
    func sheet(title: String,
               message: String,
               buttons: (cancel: String, ensure: String),
               handle: Handle? = nil) {

        _sheet(title: title, message: message, buttons: buttons, handle: handle)
    }

    /// 双按钮消息弹框，这里为了限制至少传入一个标题或消息
    private func _sheet(title: String?,
                        message: String?,
                        buttons: (cancel: String, ensure: String),
                        handle: Handle? = nil) {

        let sheet = PTPlainSheetView()
        sheet.title = title
        sheet.message = message
        sheet.buttons = buttons

        self.sheet(PTSheetHandle.Content(sheet: sheet), handle: handle)
    }
}

/// 可配置的弹框协议
extension PTPlainSheetView: PTSheetConfigurable {
    var handle: PTSheetHandle.Handle? {
        get {
            return completeHandle
        }
        set {
            completeHandle = newValue
        }
    }

    func shouldUpdateLayoutConstraints() {

        self.snp.remakeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.lessThanOrEqualTo(430)
            make.left.equalToSuperview().offset(50).priority(.high)
            make.right.equalToSuperview().offset(-50).priority(.high)
        }
    }
}

/// 双按钮弹框
class PTPlainSheetView: UIView {

    private let titleLabel: UILabel = {
        let label = UILabel(frame: .zero)
        label.numberOfLines = 0
        label.textColor = .darkText
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 18)
        return label
    }()

    private let messageLabel: UILabel = {
        let label = UILabel(frame: .zero)
        label.numberOfLines = 0
        label.textColor = .grayText
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }()

    private let cancelButton: UIButton = {
        let button = UIButton(type: .system)
        if #available(iOS 13.0, *) {
            button.backgroundColor = .systemGroupedBackground
        } else {
            button.backgroundColor = .groupTableViewBackground
        }
        button.layer.cornerRadius = 17.5
        button.setTitleColor(.systemGray, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.addTarget(self, action: #selector(cancelButtonClicked), for: .touchUpInside)
        return button
    }()

    private let ensureButton: UIButton = {
        let button = UIButton(type: .system)
        button.layer.cornerRadius = 17.5
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = .systemOrange
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.addTarget(self, action: #selector(ensureButtonClicked), for: .touchUpInside)
        return button
    }()

    private var messageTopConstraint: Constraint?
    private var buttonTopConstraint: Constraint?
    private var completeHandle: PTSheetHandle.Handle?

    var title: String? {
        didSet {
            if title == nil {
                self.messageTopConstraint?.update(offset: 0)
            } else {
                self.messageTopConstraint?.update(offset: 20)
            }
            self.titleLabel.text = title
        }
    }

    var message: String? {
        didSet {
            self.messageLabel.text = message

            if message == nil {
                self.buttonTopConstraint?.update(offset: 0)
            } else {
                self.buttonTopConstraint?.update(offset: 20)
            }
        }
    }

    var buttons: (cancel: String, ensure: String) = ("取消","确认") {
        didSet {
            self.cancelButton.setTitle(buttons.cancel, for: .normal)
            self.ensureButton.setTitle(buttons.ensure, for: .normal)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.layer.cornerRadius = 8
        self.layer.masksToBounds = true
        self.backgroundColor = .viewBackgroundColor

        self.addSubview(titleLabel)
        self.addSubview(messageLabel)
        self.addSubview(cancelButton)
        self.addSubview(ensureButton)

        renderContentView()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func renderContentView() {
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self).offset(30)
            make.left.equalTo(self).offset(50)
            make.right.equalTo(self).offset(-50)
        }

        messageLabel.snp.makeConstraints { (make) in
            self.messageTopConstraint = make.top.equalTo(titleLabel.snp.bottom).constraint
            make.left.equalTo(self).offset(20)
            make.right.equalTo(self).offset(-20)
        }

        cancelButton.snp.makeConstraints { (make) in
            self.buttonTopConstraint = make.top.equalTo(messageLabel.snp.bottom).constraint
            make.left.equalTo(self).offset(20)
            make.right.equalTo(ensureButton.snp.left).offset(-10)
            make.height.equalTo(35)
            make.bottom.equalTo(self).offset(-20).priority(.high)
        }

        ensureButton.snp.makeConstraints { (make) in
            make.top.equalTo(cancelButton)
            make.right.equalTo(self).offset(-20)
            make.size.equalTo(cancelButton)
        }
    }

    @objc private func cancelButtonClicked() {
        completeHandle?(.cancel)
    }

    @objc private func ensureButtonClicked() {
        completeHandle?(.ensure)
    }
}

private extension UIColor {
     static var darkText: UIColor {
        if #available(iOS 13.0, *) {
            return UIColor(dynamicProvider: { (trait) -> UIColor in
                if trait.userInterfaceStyle == .dark {
                    return .systemGray2
                }
                return .black
            })
        } else {
            return .black
        }
    }

    static var grayText: UIColor {
        return .systemGray
    }

    static var viewBackgroundColor: UIColor {
         if #available(iOS 13.0, *) {
            return .systemBackground
        } else {
            return .white
        }
    }
}
